<template>
  <div class="user-list-container">
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="searchForm.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
            <el-option label="保密" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增用户</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" min-width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="130"></el-table-column>
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          <span>{{ getSexText(scope.row.sex) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" v-model="dialogVisible" width="550px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
            <el-radio label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getUserList, addUser, updateUserStatus } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  username: '',
  name: '',
  phone: '',
  sex: '',
  status: '',
  page: 1,
  pageSize: 10
})

const searchFormRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 添加用户表单
const dialogVisible = ref(false)
const userForm = reactive({
  username: '',
  name: '',
  password: '',
  phone: '',
  sex: ''
})

const userFormRef = ref(null)
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const res = await getUserList(searchForm)
    console.log('获取用户列表响应数据:', res)
    
    // 正确处理后端返回的数据结构
    if (res && res.data) {
      if (res.data.records) {
        // 处理PageResult格式
        tableData.value = res.data.records
        total.value = res.data.total
      } else if (Array.isArray(res.data)) {
        // 处理直接返回数组的情况
        tableData.value = res.data
        total.value = res.data.length
      }
    } else if (res && res.records) {
      // 直接返回PageResult对象的情况
      tableData.value = res.records
      total.value = res.total
    } else if (Array.isArray(res)) {
      // 直接返回数组的情况
      tableData.value = res
      total.value = res.length
    } else {
      // 数据格式不符合预期
      console.error('返回的数据格式不符合预期:', res)
      tableData.value = []
      total.value = 0
    }
    
    // 如果没有获取到数据，加载模拟数据（仅用于测试）
    if (tableData.value.length === 0 && process.env.NODE_ENV === 'development') {
      console.warn('未获取到真实数据，加载模拟数据')
      loadMockData()
    }
  } catch (error) {
    console.error('加载用户列表失败', error)
    ElMessage.error('加载用户列表失败')
    
    // 加载失败时使用模拟数据（仅用于测试）
    if (process.env.NODE_ENV === 'development') {
      console.warn('加载失败，使用模拟数据')
      loadMockData()
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  loadUserList()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  searchForm.page = 1
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  dialogVisible.value = true
  userFormRef.value && userFormRef.value.resetFields()
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addUser(userForm)
        ElMessage.success('添加用户成功')
        dialogVisible.value = false
        loadUserList()
      } catch (error) {
        ElMessage.error(error.message || '添加用户失败')
      }
    }
  })
}

// 修改用户状态
const handleStatusChange = async (row) => {
  try {
    await updateUserStatus(row.status, row.id)
    ElMessage.success(`用户已${row.status === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1 // 恢复原状态
    ElMessage.error('修改用户状态失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  searchForm.page = val
  loadUserList()
}

// 获取性别显示文本
const getSexText = (sex) => {
  if (sex === '1') return '男'
  if (sex === '2') return '女'
  if (sex === '0') return '保密'
  return sex || '未知'
}

// 页面加载时获取数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 